package org.example.rental.utils;

import org.example.rental.entity.Permission;
import org.example.rental.vo.RouteVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author ：xxx
 * @description：TODO
 * @date ：2025/1/6 19:43
 */
public class RouteTreeUtils {
    public static List<RouteVO> buildRouteTree(List<Permission>permissionList, int pid){
            List<RouteVO> routeVOList = new ArrayList<>();
            // 从权限列表中筛选出父ID为pid的权限，并为每个权限构建一个RouteVO实例
            Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                    .stream()
                    .filter(permission -> permission != null &&
                            permission.getPid() == pid)
                    .forEach(permission -> {
                        RouteVO routeVO = new RouteVO();
                        routeVO.setPath(permission.getRoutePath());// 设置路由路径
                        routeVO.setName(permission.getRouteName());// 设置路由名称
                        // 判断是否为根路径菜单，并设置相应的组件和显示属性
                        if (permission.getPid() == 0) {
                            routeVO.setComponent("Layout");
                            routeVO.setAlwaysShow(true);
                        } else {
                            routeVO.setComponent(permission.getRouteUrl());
                            routeVO.setAlwaysShow(false);
                        }
                        // 设置路由的元信息，包括权限标签、图标和权限代码
                        routeVO.setMeta(routeVO.new
                                Meta(permission.getPermissionLable(),
                                permission.getIcon(),
                                permission.getPermissionCode().split(",")));
                        // 递归构建该权限下的子路由树
                        List<RouteVO> children = buildRouteTree(permissionList,
                                permission.getId());
                        routeVO.setChildren(children);
                        routeVOList.add(routeVO);
                    });
            return routeVOList;
    }
}
